<!DOCTYPE html>
<html>
	<head>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
		<link href="{{ url_for('static', filename='style.less') }}" rel="stylesheet/less" type="text/css">
		<script src="{{ url_for('static', filename='less.js') }}" type="text/javascript"></script>
		<meta charset="utf-8">
		<title>sinple</title>
	</head>
	<body>
		<div id="main">
			<div class="msg success" style="display: none">
				<span>Erfolg</span>
			</div>
			<div class="msg error" style="display: none">
				<span>Fehler</span>
			</div>
			<div id="form">
				<form action="/" id="note">
					<div id="inputs">
						<input id="title" name="title" type="text"/>
						<textarea id="text" name="text"></textarea>
					</div>
					<div id="buttons">
						<input id="save" type="submit" value="Speichern"/>
						<button id="reset">
							Zurücksetzen
						</button>
						<input id="filename" name="filename" type="hidden"/>
					</div>
				</form>
			</div>
			<div id="notes">
				<ul id="list"></ul>
			</div>
		</div>
		<script>
			$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
			$(document).ready(function() {

				var get_note_list = function() {
					$.getJSON($SCRIPT_ROOT + '/_get_note_list', {}, function(data) {
						$("#list").empty();
						$.each(data.result, function(key, value) {
							$("#list").append('<li><a class="note" href="" id="' + key + '">' + value + '</a></li>');
						});
					});
				}
				get_note_list();

				$("#note").submit(function(e) {
					e.preventDefault();
					var title = $(this).find('input[name="title"]').val();
					var text = $(this).find('textarea[name="text"]').val();
					var filename = $(this).find('input[name="filename"]').val();
					var url = $SCRIPT_ROOT + '/_save_note';
					$.post(url, {
						'title' : title,
						'text' : text,
						'filename' : filename
					});
				});

				$('button#reset').click(function(e) {
					e.preventDefault();
					$('#title').val('');
					$('#text').val('');
					$('#filename').val('');
					$('#save').val('Speichern');
				});

				$('a.note').live('click', function(e) {
					var filename = $(this).attr('id');
					var title = $(this).text();
					$.getJSON($SCRIPT_ROOT + '/_get_note_text', {
						'filename' : filename
					}, function(data) {
						$('#title').val(title);
						$('#text').val(data.result);
						$('#filename').val(filename);
						$('#save').val('"' + title + '" speichern');
					});
					return false;
				});

				$("div.msg.success").ajaxSuccess(function(event, request, settings) {
					if(settings.url == $SCRIPT_ROOT + '/_save_note') {
						get_note_list();
						$(this).show().delay(2000).fadeOut('slow');
					}
				});
				$("div.msg.error").ajaxError(function(event, request, settings) {
					if(settings.url == $SCRIPT_ROOT + '/_save_note') {
						get_note_list();
						$(this).show().delay(2000).fadeOut('slow');
					}
				});
			});

		</script>
	</body>
</html>

